package com.learn.security.theory.use;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;

public class RestTemplateUtil {

    private static class SingletonRestTemplate {
        /**
         * 单例对象实例
         */
        static final RestTemplate INSTANCE = new RestTemplate();
    }

    /**
     * 单例实例
     */
    public static RestTemplate getInstance() {
        return SingletonRestTemplate.INSTANCE;
    }

    /**
     * 发送post请求
     *
     * @param url 请求URL地址
     */
    public static String get(String url)
            throws Exception {
        HttpHeaders headers = new HttpHeaders();
         /*headers.add(HttpHeadersImpl.ACCEPT, "application/json");
        headers.add(HttpHeadersImpl.ACCEPT_ENCODING, "gzip");
        headers.add(HttpHeadersImpl.CONTENT_ENCODING, "UTF-8");
        headers.add(HttpHeadersImpl.CONTENT_TYPE,
                "application/json; charset=UTF-8");
        headers.add(HttpHeadersImpl.COOKIE, token);
        headers.add("Token", token);*/
        headers.add("Accept", "application/json");
        headers.add("Accpet-Encoding", "gzip");
        headers.add("Content-Encoding", "UTF-8");
        headers.add("Content-Type", "application/json; charset=UTF-8");
//        headers.add("Token", token);

        HttpEntity<String> formEntity = new HttpEntity<>(headers);

        return RestTemplateUtil.getInstance().getForObject(url, String.class, formEntity);
    }

    /**
     * 发送post请求
     *
     * @param url   请求URL地址
     * @param data  json数据
     * @param token RSA加密token【RSA({PlatformCode+TenantCode+DateTime.Now()})//平台代码
     *              +会员/租户代码+当前时间，然后进行RSA加密】
     */
    public static String post(String url, String data, String token)
            throws Exception {
        HttpHeaders headers = new HttpHeaders();
         /*headers.add(HttpHeadersImpl.ACCEPT, "application/json");
        headers.add(HttpHeadersImpl.ACCEPT_ENCODING, "gzip");
        headers.add(HttpHeadersImpl.CONTENT_ENCODING, "UTF-8");
        headers.add(HttpHeadersImpl.CONTENT_TYPE,
                "application/json; charset=UTF-8");
        headers.add(HttpHeadersImpl.COOKIE, token);
        headers.add("Token", token);*/
        headers.add("Accept", "application/json");
        headers.add("Accpet-Encoding", "gzip");
        headers.add("Content-Encoding", "UTF-8");
        headers.add("Content-Type", "application/json; charset=UTF-8");
        headers.add("Token", token);

        HttpEntity<String> formEntity = new HttpEntity<>(data, headers);
        return RestTemplateUtil.getInstance().postForObject(url, formEntity, String.class);
    }


}
